
space = "&nbsp;" 
tab = space * 4

def generate():
	count = 0

	outFile = open("doc/grammar.html", "w")

	outFile.write("""
<html>
<head>
<style TYPE="text/css">
A:link{text-decoration:none}
A:visited{text-decoration:none}
A:hover {color: #ff00ff;text-decoration:underline}
</style>
<title>Grammar</title>
</head>
<body>
""")

	isBegin = False
	isCode = False
	for line in open("grammar.y", "r"):
		if len(line.strip()) == 0:
			continue

		if isBegin:
			if line[:2] == "%%":
				break
		else:
			if line[:2] == "%%":
				isBegin = True
			continue
		
		if line[0] == "{":
			isCode = True
			continue
		if line[0] == "}":
			isCode = False
			continue
		if isCode:
			continue
				
		if line.startswith("\t"):
			line = line.strip()
			if line[0] == ";":
				outFile.write("<br>\n")
				continue
			elif line[0] == "|":
				outFile.write(tab + "|" + space * 3)
				line = line[1:].strip()
			else:
				outFile.write(tab * 2)
			
			strs = line.split()
			isComment = False
			isPrec = False

			for str in strs:
				outFile.write(space * 2)

				if str == "/*":
					isComment = True

				if isPrec:
					isPrec = False
					outFile.write('<font color="green">' + str + '</font>')
				elif isComment or str[0] == "L" or str[0] == "'":
					outFile.write(str)
				elif str == "%prec":
					isPrec = True
					outFile.write('<font color="green">' + str + '</font>')
				else:
					outFile.write('<a href="#%s">%s</a>' % (str, str))

				if str == "*/":
					isComment = False

			outFile.write("<br>\n")
		else:
			count += 1
			str = line.strip()[:-1]
			outFile.write('<a name="%s"><b>%s</b></a>:<br>\n' % (str, str))

	outFile.write('<a name="error"><b>error</b></a>:<br>\n')
	outFile.write("</body>\n")
	outFile.write("</html>\n")

	print "Total: %d" % count

if __name__=="__main__":
	generate()
